﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StudyCode.ORM.Entities;

namespace StudyCode.ORM.Repository
{
    public class Repository<TEntity> : IRepository<TEntity> where TEntity : Entity,new()
    {
        public virtual TEntity Get(long id)
        {
            string sqlStr = SqlBuilder.Get<TEntity>(id);
            using (var sqlDataReader = SqlHelper.ExecuteReader(SqlHelper.GetConnection(), CommandType.Text, sqlStr))
            {

                //判断是否刻度，并且在使用数据前一定要运行才能读取
                if (!sqlDataReader.Read())
                    return null;
                var entity = new TEntity();
                
                typeof(TEntity).GetProperties()
                    .Where(item => item.PropertyType.IsValueType || item.PropertyType == typeof(string))
                    .ToList()
                    .ForEach(property => property.SetValue(entity, sqlDataReader[property.Name]));
                return entity;
            }
        }

        public virtual  void Insert(TEntity entity)
        {
            string sqlStr = SqlBuilder.InsertBuild(entity);
            SqlHelper.ExecuteNonQuery(SqlHelper.GetConnection(), CommandType.Text, sqlStr);
        }

        public virtual void Update(TEntity entity)
        {
            string sqlStr = SqlBuilder.UpdateBuild(entity);
            SqlHelper.ExecuteNonQuery(SqlHelper.GetConnection(), CommandType.Text, sqlStr);
        }

        public virtual void Delete(TEntity entity)
        {
            string sqlStr = SqlBuilder.DeleteBuild(entity);
            SqlHelper.ExecuteNonQuery(SqlHelper.GetConnection(), CommandType.Text, sqlStr);
        }

        public virtual List<TEntity> GetAll()
        {
            string sqlStr = SqlBuilder.GetAllBuild<TEntity>();
            var dataset = SqlHelper.ExecuteDataset(SqlHelper.GetConnection(), CommandType.Text, sqlStr);
            var list = new List<TEntity>();
            foreach (DataRow row in dataset.Tables[0].Rows)
            {

                var entity = new TEntity();
                typeof(TEntity).GetProperties()
                    .Where(item => item.PropertyType.IsValueType || item.PropertyType == typeof(string))
                    .ToList()
                    .ForEach(property => property.SetValue(entity, row[property.Name]));
                list.Add(entity);
            }
            return list;
        }
    }
}
